﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Huinn.Common.XML
{
    public class Utilities
    {
        public static XmlElement InitializeXml(XmlDocument doc, string rootName)
        {
            if (doc == null)
                return null;

            // insert declaration as first element
            XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", null, "yes");
            doc.InsertBefore(declaration, doc.DocumentElement);

            // insert root element
            XmlElement rootElement = doc.CreateElement(rootName);
            doc.InsertAfter(rootElement, declaration);

            return rootElement;
        }
        public static XmlDocument RetrieveDocument(string docUrl, System.Web.HttpServerUtility server)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(server.MapPath(docUrl));
            return doc;
        }

        /// <summary>
        /// Deserializes the given form data given a class type
        /// </summary>
        /// <typeparam name="T">form class</typeparam>
        /// <param name="data">form data</param>
        /// <returns>deserialized class</returns>
        public static T DeserializeFormData<T>(string data)
        {
            T tmp;
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (XmlTextReader reader = new XmlTextReader(new System.IO.StringReader(data)))
            {
                tmp = (T)serializer.Deserialize(reader);
                reader.Close();
            }
            return tmp;
        }

        /// <summary>
        /// Serializes a class to a string
        /// </summary>
        /// <typeparam name="T">The type of class to be serialized</typeparam>
        /// <param name="data">The instance of the class to serialize</param>
        /// <returns>serialized class</returns>
        public static string SerializeFormData<T>(T data)
        {
            byte[] bytes;
            //Serialize formdata into bytes and return
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(stream, data);
                stream.Position = 0;
                bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
            }
            return Encoding.UTF8.GetString(bytes);
        }
    }
}
